from django.utils.deprecation import MiddlewareMixin
from account import models
from django.shortcuts import redirect
from django.conf import settings
import datetime
import re

class Universe(object):

    def __init__(self):
        self.user = None
        # self.price_policy = None
        # self.project = None

class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        """ 如果用户已登录，则request中赋值 """

        request.universe = Universe()

        user_id = request.session.get('user_id', 0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()
        request.universe.user = user_object

        # 白名单：没有登录都可以访问的URL
        """
        1. 获取当用户访问的URL
        2. 检查URL是否在白名单中，如果在则可以继续向后访问，如果不在则进行判断是否已登录
        """
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return

        # 检查用户是否已登录，已登录继续往后走；未登录则返回登录页面。
        if not request.universe.user:
            return redirect('login')


"""
    # 因为要先通过process_request获取project信息，才能判断进入了哪个项目中，然后再使用process_view()获取信息后进入视图函数
    def process_view(self, request, view, args, kwargs):

        # 判断URL是否是以/tbug/manage/开头，如果是则判断项目ID是否是我创建 or 参与
        if not request.path_info.startswith('/tbug/manage/'):
            return

        project_id = kwargs.get('project_id')   # 为什么使用kwargs
        # print("这里有没有显示吖%s",project_id)
        # 是否是我创建的
        project_object = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_object:
            # 是我创建的项目的话，我就让他通过
            request.tracer.project = project_object
            return

        # 是否是我参与的项目
        project_user_object = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        if project_user_object:
            # 是我参与的项目
            request.tracer.project = project_user_object.project
            return

        return redirect('project_list')
"""